<?php
/**
* This is the main entry request from client side
*
* @category CDF-91680
* @package  Core
* @author Guillaume Didelot
* @license Open source
* @link http://www.cdf-91680.fr/Core/server.class.php
*/

namespace Core;
session_start();

//Declare constantes
define('CORE_DIR', __Dir__ . '/') ;
define('COMMONS_DIR', CORE_DIR .'CoreCommons/');
define('COMPONENTS_DIR', CORE_DIR .'CoreComponents/');
define('CONTRACTS_DIR', CORE_DIR .'CoreContracts/');
define('SERVICES_DIR', CORE_DIR .'CoreServices/');
define('DATASTORAGE_DIR', CORE_DIR .'Datastorage/');

//Commons references
require_once(COMMONS_DIR . 'parameters.class.php');
require_once(COMMONS_DIR . 'logger.class.php');
require_once(COMMONS_DIR . 'localization.class.php');
require_once(COMMONS_DIR . 'comlistener.class.php');
require_once(COMMONS_DIR . 'serviceresponse.class.php');
require_once(COMMONS_DIR . 'mail.class.php');

//Services facade reference
require_once(CORE_DIR . 'coreservice.class.php');

//Components included
require_once(COMPONENTS_DIR . 'AccountingManager/Accounts.php');
require_once(COMPONENTS_DIR . 'AccountingManager/Operations.php');
require_once(COMPONENTS_DIR . 'AccountingManager/Categories.php');
require_once(COMPONENTS_DIR . 'DocumentsManager/Documents.php');
require_once(COMPONENTS_DIR . 'TasksManager/Tasks.php');
require_once(COMPONENTS_DIR . 'UsersManager/Users.php');
require_once(COMPONENTS_DIR . 'ArticlesManager/Articles.php');
require_once(COMPONENTS_DIR . 'EventsManager/Events.php');
require_once(COMPONENTS_DIR . 'TchatsManager/Tchats.php');
require_once(COMPONENTS_DIR . 'LogisticManager/Materials.php');

//Commons tools references
require_once(COMMONS_DIR . 'logger.class.php');

//DataStorage required references
require_once(DATASTORAGE_DIR . 'session.class.php');
require_once(DATASTORAGE_DIR . 'Tools/managedump.class.php');
require_once(DATASTORAGE_DIR . 'Tools/resetmappings.class.php');

try
{
	if(isset($_GET["action"]))
	{
		$action = $_GET["action"];

		if($action == "validemail")
		{
			$token = $_GET["token"];
			
			if(isset($token))
			{
				$service = new CoreService();
				
				$result = $service->validUserEmail($token);
				
				if($result->isFailed == false)
				{	
					header('Location: http://localhost:8080/projects/CDF91680/Sources/GUI/Views');
					exit;
				}
				else
				{
					var_dump($result);
				}
			}
		}
	}
	else
	{
		if ( !empty( $_FILES ) ) 
		{
			try
			{
				CoreCommons\Logger::Debug("Files detected");
				
				$tmpName = $_FILES['file']['tmp_name'];
				$name = $_FILES['file']['name'];
				$mime = $_FILES['file']['type'];
				$path = $_FILES['file']['name'];
				$size = $_FILES['file']['size'];
			
				$fp      = fopen($tmpName, 'r');
				$blob = fread($fp, filesize($tmpName));
				fclose($fp);
				
				if($size > 1000000)
				{
					$result = CoreCommons\ServiceResponse::CreateError(new \Exception("La taille du fichier dépasse 1 Mo : $size"));
				}
				else
				{
					CoreCommons\Logger::Debug("File size to process is $size");
					$tempPath = $_FILES[ 'file' ][ 'tmp_name' ];
					$extension = pathinfo($path, PATHINFO_EXTENSION);
					
					CoreCommons\Logger::Debug("File parameters are mime $mime, extension $extension");
					
					$service = new CoreService();
					
					if(isset($_POST['service']) == false)
					{
						throw new \Exception("Service is not set");
					}
					
					$result = null;
					
					if($_POST['service'] == "attachAvatarOnAnUser")
					{
						$idUser = $_POST['idUser'];
						
						$result = $service->attachAvatarOnAnUser($idUser, $blob, $mime, $extension);
					}
					else if($_POST['service'] == "attachPosterOnAnEvent")
					{
						$idEvent = $_POST['idEvent'];
						
						$result = $service->attachPosterOnAnEvent($idEvent, $blob, $mime, $extension);
					}
					
					else if($_POST['service'] == "attachEventAttachment")
					{
						$eventId = $_POST['eventId'];
						
						$result = $service->attachEventAttachment($eventId, $name, $blob, $mime, $extension);
					}
					
					else if($_POST['service'] == "uploadDocument")
					{
						$rootpath = $_POST['rootpath'];
						
						$result = $service->uploadDocument($tempPath, $rootpath, $path);
					}
					
					else if($_POST['service'] == "uploadDocument")
					{
						$rootpath = $_POST['rootpath'];
						
						$result = $service->uploadDocument($tempPath, $rootpath, $path);
					}

				}
				CoreCommons\ComListener::SendData($result);
			}
			catch(\Exception $ex)
			{
				CoreCommons\Logger::Error($ex->getMessage());
			}
		}
		else
		{
			$data = CoreCommons\ComListener::GetDatas();

			$service = $data->service;
			
			if($service == "" || $service == null)
			{
				throw new \Exception("The service name have to be filled.");
			}
			
			//Get all method parameters and set all provided parameters
			$method = new \ReflectionMethod('Core\CoreService', $service);
			$params = $method->getParameters();
			
			CoreCommons\Logger::Info("Server call $service");
			
			$class = new \ReflectionClass('Core\CoreService'); 
			$objectInstance = $class->newInstanceArgs();
			
			$result = null;
			
			if(count($params) == 0)
			{
				$result = call_user_func_array(array($objectInstance, $service), array());
			}
			else
			{
				//Compute all parameters to send at the targeted method
				$values = array();
				foreach ($params as $param) 
				{
					$paramName = $param->getName();
					if(isset($data->$paramName))
					{
						$values[] = $data->$paramName;
					}
				}

				$result = call_user_func_array(array($objectInstance, $service), $values);
			}

			CoreCommons\ComListener::SendData($result);
		}
	}
}
catch (\Exception $ex) 
{
	CoreCommons\Logger::Error($ex->getMessage());
}
?>